<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .list-item{
            display: flex;
            width: 200px;
            height: 30px;
            justify-content:space-between;
            align-items:center;
        }

        .price-container{
            display: flex;
            width: 100px;
            height:100%;
            align-items:center;
        }
    </style>
</head>
<body>
    <div id="app">
        <list-item v-for="(item,index) in list" 
                :item="item" :index="index"
                :key="index"
                @add="addHandler"
                @sub="subHandler"
        ></list-item>

        <div>
            总价:{{ total | currencyRMB }}
        </div>
    </div>

    <script src="https://cdn.jsdelivr.net/npm/vue/dist/vue.js"></script>
    <script>
        Vue.filter('currencyRMB',(v)=>{
    // return '¥' + v.fixed(2);

    return `¥${v.toFixed(2)}`
})

const listItem = {
    template : `
        <div class='list-item'>
            <div> {{ item.name }}</div>
            <div class="price-container">
                <div>{{ item.price | currencyRMB }}</div>
                <div @click='sub'>-</div>
                <div>{{ item.count }}</div>
                <div @click='add'>+</div>
            </div>
        </div>
    `,
    props:{
        item : {
            type : Object,
            default : {}
        },
        index: {
            type: Number
        }
    },
    methods:{
        add(){
            // ? 修改props
            // ? 修改状态，修改原组件状态
            // this.item.count ++;
            this.$emit('add',this.index);
        },
        sub(){
            this.$emit('sub',this.item)
        }
    }
}


let vm = new Vue({   
    el:'#app',
    components:{
        'list-item' : listItem
    },
    data(){
        return {
            list:[
                { name : '香蕉',price: 10,count : 1 },
                { name : '苹果',price: 20,count : 1 },
                { name : '榴莲',price: 30,count : 1 },
                { name : '葡萄',price: 50,count : 1 },
            ],
            // msg : '123'
        }
    },
    computed: {
        total(){
            let sum = 0;
            this.list.forEach((item)=>{
                sum += item.count * item.price
            })
            return sum;
        }
    },
    methods:{
        addHandler(index){
            this.list[index].count ++;
        },
        subHandler(item){
            // ? 应用数据类型，传递对象的时候是内存地址
            // ? 所以item和this.list[index]是同一个
            item.count --;
        }
    }
});
    </script>
</body>
</html>